package vip.zhenzicheng.rabbitmq.workqueue;

import com.rabbitmq.client.*;
import vip.zhenzicheng.rabbitmq.utils.RabbitConstant;
import vip.zhenzicheng.rabbitmq.utils.RabbitUtils;

import java.io.IOException;

/**
 * @author zhenzicheng
 * @DESCRIPTION: 短信发送服务1 (消费者)
 * @DATE: 2022/04/24 3:18 PM
 */
public class SMSSender1 {
  public static void main(String[] args) throws IOException {
    Connection conn = RabbitUtils.getConnection();
    final Channel channel = conn.createChannel();

    channel.queueDeclare(RabbitConstant.QUEUE_SMS, false, false, false, null);
    /*
     * 如果不写basicQos(1) 则MQ自动将所有请求平均发送给所有消费者
     * 如果指定则MQ不会一次性发送多个请求，而是等消费者处理完一个消息(确认后)，再从队列中获取一个新的消息
     */
    channel.basicQos(1);

    channel.basicConsume(RabbitConstant.QUEUE_SMS, false, new DefaultConsumer(channel) {
      @Override
      public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        String jsonSMS = new String(body);
        System.out.println("SMSSender1-短信发送成功" + jsonSMS);
        try {
          // 模拟性能最好的服务器
          Thread.sleep(10);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }

        channel.basicAck(envelope.getDeliveryTag(), false);
      }
    });

  }
}
